package cn.backpackerxl.easyJDBC.util;

import java.io.*;
import java.net.URL;
import java.util.Locale;

/**
 * @Author: backpackerxl
 * CreateTime: 2022/5/19
 * FileName: SerializeField
 **/
public final class SerializeField {
    private final static URL path = SerializeField.class.getResource("/");

    private SerializeField() {
    }

    private static String getName(String name) {
        String[] names = name.split("[.]");
        return "old" + names[names.length - 1].toLowerCase(Locale.ROOT);
    }

    public static void serialize(String name, FieldObject fieldObject) {
        ObjectOutputStream outputStream;
        try {
            outputStream = new ObjectOutputStream(new FileOutputStream(path.getPath() + getName(name)));
            outputStream.writeObject(fieldObject);
            Logger.logger(getName(name) + " serialize success.");
        } catch (IOException e) {
            Logger.error(getName(name) + " serialize error.");
            e.printStackTrace();
        }
    }

    public static FieldObject deserialization(String name) {
        ObjectInputStream inputStream;
        FieldObject fieldObject = null;
        try {
            inputStream = new ObjectInputStream(new FileInputStream(path.getPath() + getName(name)));
            fieldObject = (FieldObject) inputStream.readObject();
            Logger.logger(getName(name) + " deserialization success.");
        } catch (IOException | ClassNotFoundException e) {
            Logger.logger(getName(name) + " deserialization error.");
            e.printStackTrace();
        }
        return fieldObject;
    }

    public static boolean exist(String name) {
        return new File(path.getPath() + getName(name)).exists();
    }
}
